package org.neogenesis.web.loader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;

public class ProbesLoaderArrayExpress extends ProbesLoader {

	private String[] columns;

	private int idColumn;

	public ProbesLoaderArrayExpress(String pathPlatform) throws IOException {
		URL url = new URL(pathPlatform);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		if (conn.getResponseCode() != 200) {
			throw new IOException(conn.getResponseMessage());
		}

		BufferedReader rd = new BufferedReader(new InputStreamReader(
				conn.getInputStream()));

		String line;
		this.rows = new LinkedList<String[]>();

		while ((line = rd.readLine()) != null) {
			if (line.length() == 0)
				break;
		}

		columns = rd.readLine().split("\t");

		for (int i = 0; i < columns.length; i++) {
			if (columns[i].contains("[")) {
				columns[i] = columns[i].substring(columns[i].indexOf("[") + 1,
						columns[i].indexOf("]"));
			}
		}

		defineFileType();

		while ((line = rd.readLine()) != null) {
			String[] splitLine = line.split("\t");
			
			// non salvare in rows le righe con meno di
			// "idColumn+1" colonne
			if (splitLine.length -1 < idColumn)
				continue;
			
			if (splitLine[idColumn].length() == 0)
				continue;
			
			//non salvare le righe che contengono "---" 
			//in posizione idColumn
			if (splitLine[idColumn-1].equalsIgnoreCase("---"))
				continue;
			
			rows.add(splitLine);
		}

	} 

	@Override
	protected void defineFileType() {

		typeMetaPlatform = TypeMetaPlatform.NONE;
		TypeMetaPlatform temp;

		// scorre le colonne alla ricerca di un typeMetaPlatform con priorità
		// superiore a NONE

		for (int i = 0; i < columns.length; i++) {

			temp = TypeMetaPlatform.getByContainment(columns[i].toUpperCase());
			if (temp.priority() > typeMetaPlatform.priority()) {
				typeMetaPlatform = temp;
				idColumn = i;
			}

		}

	}

	@Override
	public int getIdColumn() {
		// TODO Auto-generated method stub
		return idColumn;
	}
}